<template>
  <div class="section section-one">
    <div class="title">
      <span>航标统计</span>
    </div>
    <div class="content">
      <div class="sub-title">
        <span class="title" v-show="!outer">
          <!-- 报警等级 -->{{ subTitle }}
        </span>
        <span class="self-icon" v-show="!outer" @click="backChart">
          <el-icon :size="'large'" :color="'#ffffff'">
            <Back />
          </el-icon>
        </span>
      </div>
      <div class="dialog-inner" v-loading="loading" element-loading-background="rgba(18, 25, 58, 0.8)">
        <div class="main-chart-ref" ref="MainChartRef">

        </div>
      </div>
      <div class="divider" v-show="!isShow"></div>
      <span class="title echarts_Titile" v-show="!isShow">
        <!-- 报警类型{} -->
        {{ subTitle1 }}
      </span>
      <div class="main-chart-ref" ref="MainChartRef1" v-show="!isShow">

      </div>
    </div>
  </div>
</template>
<script>
let ChartIns = null;
let ChartIns1 = null;
import Api from '@/api';
import eventBus from '@/utils/eventBus.js'
export default {
  name: "SectionOne",
  components: {},
  props: {},
  data() {
    return {
      outer: true,
      countOfShipInSocial: '---',
      color: ["#3ae6ff", "#64fb52", "#fecc37", "#fccc30"],
      // 在册数据
      policeColor: ['#6E6BFC', '#407FFF', '#F69D33', '#3BEB75', '#40D8F9', '#AED31A', '#C9E5AE', '#0AF3D3', '#Dc413C', '#FFC0CB'],
      policeLevel: [{ name: '1级', value: 516 }, { name: '2级', value: 14 }, { name: '提示', value: 120 }, { name: '未确认', value: 350 }],
      policeType: [{ name: '终端故障', value: 16 }, { name: '参数未同步', value: 295 }, { name: '航标灯报警', value: 100 }, { name: '灯通讯报警', value: 16 }, { name: '电压报警', value: 100 }, { name: '定位无效', value: 201 }, { name: '位移报警', value: 44 }, { name: '漂移报警', value: 228 }, { name: '超时报警', value: 228 }, { name: '终端电压报警', value: 228 }],
      policeType1: [{ name: '类型5', value: 16 }, { name: '类型6', value: 100 }, { name: '类型7', value: 201 }, { name: '类型8', value: 44 }],
      isShow: true,
      // 设计
      beRegisteredData: [],
      // 实装
      actualData: [{ name: "宜宾", value: 203 }, { name: "重庆", value: 394 }, { name: "泸州", value: 404 }, { name: "涪陵", value: 441 }, { name: "万州", value: 388 }, { name: "宜昌", value: 381 }, { name: "荆州", value: 303 }, { name: "岳阳", value: 283 }, { name: "武汉", value: 521 }, { name: "九江", value: 190 }, { name: "芜湖", value: 589 }, { name: "南京", value: 213 }, { name: "镇江", value: 324 }, { name: "上海", value: 424 }],
      isClickOne: false,
      isClickTwo: false,
      navigationAids: [{ name: "航行标志", value: 29 }, { name: "信号标志", value: 129 }, { name: "专用标志", value: 59 }, { name: "警示标志", value: 69 }],
      flag: 1,
      loading: true
    };
  },
  computed: {
    subTitle() {
      return !this.isShow ? !this.isClickTwo ? '报警等级' : this.isClickOne ? '航标设标数' : '实装航标数' : !this.isClickOne ? '实装航标数' : '航标设标数';
    },
    subTitle1() {
      return !this.isShow ? this.isClickTwo ? '航标类型' : '报警类型' : '航标类型';
    }
  },
  mounted() {
    this.initChart();

  },
  unmounted() {
    if (ChartIns) {
      ChartIns.dispose();
    }
  },
  methods: {
    toRGB(color, opacity) {
      if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(color)) return;
      const chars = color.split("").splice(1);
      const r = `0x${chars[0]}${chars[1]}`;
      const g = `0x${chars[2]}${chars[3]}`;
      const b = `0x${chars[4]}${chars[5]}`;
      return `rgba(${parseInt(r)},${parseInt(g)},${parseInt(b)},${typeof opacity === "number" ? opacity : "1"
        })`;
    },
    initChart() {
      this.loading = true;
      const that = this;
      let seriesDataForNavigation = window.SUPER_GIS_SPACE.fiaryWayAnalize.outer.data;
      Api.getDataOf4TagsAtBureau().then(res => {
        that.beRegisteredData = res;
      })
      let p1;
      let p2;
      if (window.SUPER_GIS_SPACE.isMockData) {

        p1 = Api.getDataByConfigApiHBCount()
        p2 = Api.getDataByConfigApiHBshiCount()
      } else {
        // 各单位航标数量统计 废弃
        p1 = Api.getDataByConfigApi({ cfgName: '数字孪生-各单位航标数量统计' })
        // 实装航标的统计
        p2 = Api.getDataByConfigApi({ cfgName: '数字孪生-各单位实装数字航标数量统计' })
      }



      const formData = new FormData();
      formData.append('plat_key', window.SUPER_GIS_SPACE.plat_key);
      formData.append('order', '-gxsj')
      formData.append('page_size', '500000')
      formData.append('begin_end', '1-10000')
      const currentDate = new Date();
      let NavEmergency = []
      // 获取当前年份、月份、日期
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth() + 1; // 注意月份是从 0 开始计算的，所以要加 1
      const currentDay = currentDate.getDate();
      // 告警航标数目
      let p3 = Api.getNavEmergency(formData)
      Promise.all([p1, p2, p3]).then(res => {
        if (res[0].data.data) {
          // that.beRegisteredData = []
          that.actualData = []
          // 设标
          seriesDataForNavigation[0] = res[0].data.data[0].Total;
          // 实装
          seriesDataForNavigation[1] = res[1].data.data[0].Total;
          // for (let key in res[0].data.data[0]) {
          //   if (key == 'Total') continue;
          //   that.beRegisteredData.push({ name: key, value: res[0].data.data[0][key] })
          // }
          for (let key in res[1].data.data[0]) {
            if (key == 'Total') continue;
            that.actualData.push({ name: key, value: res[1].data.data[0][key] })
          }
          res[2].d.results.forEach(item => {
            const targetDate = new Date(item.bjsj); // 这里假设要判断的时间是 2023 年 2 月 25 日
            // 获取要判断的时间的年份、月份、日期
            const targetYear = targetDate.getFullYear();
            const targetMonth = targetDate.getMonth() + 1;
            const targetDay = targetDate.getDate();
            if (currentYear === targetYear && currentMonth === targetMonth && currentDay === targetDay && item.bjjssj == "") {
              NavEmergency.push(item)
            }
          })
          let obj = {
            '1级': 0,
            '2级': 0,
            '提示': 0,
            '未确认': 0
          }
          let obj1 = {
            '终端故障': 0,
            "参数未同步": 0,
            '航标灯报警': 0,
            "灯通讯报警": 0,
            "电压报警": 0,
            '定位无效': 0,
            '位移报警': 0,
            '漂移报警': 0,
            "超时报警": 0,
            '终端电压报警': 0
          }
          NavEmergency.forEach(item => {
            switch (item.hb_bjdj) {
              case '3':
                obj['提示']++;
                break;
              case '2':
                obj['2级']++;
                break;
              case '1':
                obj['1级']++;
                break;
              case "":
                obj['未确认']++;
                break;
                ;
            }
            switch (item.hb_bjlx) {
              case '1':
                obj1['终端故障']++;
                break;
              case '2':
                obj1['参数未同步']++;
                break;
              case '3':
                obj1['航标灯报警']++;
                break;
              case "4":
                obj1['灯通讯报警']++;
                break;
              case '5':
                obj1['电压报警']++;
                break;
              case '6':
                obj1['定位无效']++;
                break;
              case '7':
                obj1['位移报警']++;
                break;
              case "8":
                obj1['漂移报警']++;
                break;
              case '9':
                obj1['超时报警']++;
                break;
              case "10":
                obj1['终端电压报警']++;
                break;
            }
          })
          seriesDataForNavigation[2] = NavEmergency.length;
          const chartDom = that.$refs.MainChartRef;
          ChartIns = echarts.init(chartDom);
          that.renderChart({
            xAxisName: window.SUPER_GIS_SPACE.fiaryWayAnalize.outer.name,
            seriesData: seriesDataForNavigation,
            datazoom: false,
          })
          this.loading = false;
          // 点击事件
          ChartIns.on("click", function (e) {
            switch (e.dataIndex) {
              case 2:
                // 告警
                that.resetChartDataInner(obj, obj1);
                break;
              case 1:
                // 实际
                that.resetChartDataInner1();
                break;
              default:
                // 设计
                that.resetChartDataInner2()
            }
          })
        }
      })
    },
    renderChart({ xAxisName, seriesData, datazoom }) {
      const that = this;
      const option = {
        color: that.color,
        tooltip: {
          trigger: "axis",
          textStyle: {
            align: "left"
          },
          axisPointer: {
            type: "shadow"
          }
        },
        legend: {
          align: "right",
          right: 0,
          itemHeight: 8,
          itemWidth: 20,
          show: false,
          textStyle: {
            color: "#fff"
          }
        },
        grid: {
          left: "5%",
          right: "5%",
          bottom: "5%",
          top: "15%",
          containLabel: true
        },
        yAxis: {
          type: "value",
          name: '单位（座）',
          nameTextStyle: {
            color: "#ffffff"
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "rgba(133,194,255,.5)"
            }
          },
          boundaryGap: ["0", "40%"],
          splitLine: {
            show: true,
            lineStyle: {
              color: "rgba(58,112,197,.12)"
            }
          },
          splitNumber: 2,
          axisLabel: {
            color: "#ffffff"
          },
          splitArea: {
            show: false,
            areaStyle: {
              color: "rgba(58,112,197,.1)"
            }
          }
        },
        xAxis: {
          type: "category",
          data: xAxisName,
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "rgba(133,194,255,.5)"
            }
          },
          axisLabel: {
            color: "#ffffff",
            interval: 0,
            width: 80,
            overflow: "truncate",
            ellipsis: "..."
          }
        },
        series: {
          type: 'bar',
          barMinWidth: 10,
          barMaxWidth: 15,
          label: {
            show: true,
            position: "top",
            borderColor: "transparent",
            borderWidth: 0,
            fontSize: 16,
            color: "#ffffff",
            shadowColor: "transparent",
            fontFamily: "YouSheBiaoTiHei"
          },
          itemStyle: {
            color: function (params) {
              // return new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              //   { offset: 0, color: that.color[!that.isClickTwo ? params.dataIndex : 0] },
              //   { offset: 0.985, color: that.toRGB(that.color[!that.isClickTwo ? params.dataIndex : 0], 0.1) },
              //   { offset: 0.985, color: that.toRGB(that.color[!that.isClickTwo ? params.dataIndex : 0], 1) },
              //   { offset: 1, color: that.toRGB(that.color[!that.isClickTwo ? params.dataIndex : 0], 1) }
              // ])
              return new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: "#00677B" },
                { offset: 1, color: "#90ffEF" }
              ])
            }
          },
          data: seriesData
        },
        dataZoom: [{
          type: "slider",
          show: datazoom,
          height: 10,
          start: datazoom ? 45 : 0,//位置
          end: datazoom ? 75 : 100,
          moveHandleSize: 5,
          textStyle: { color: "#fff" }
        }]
      }
      option && ChartIns.setOption(option, true);
    },

    renderChart1({ xAxisName, seriesData }) {
      const that = this;
      const option = {
        color: that.policeColor,
        tooltip: {
          trigger: "axis",
          textStyle: {
            align: "left"
          },
          axisPointer: {
            type: "shadow"
          }
        },
        legend: {
          align: "right",
          right: 0,
          itemHeight: 8,
          itemWidth: 20,
          show: true,
          textStyle: {
            color: "#fff"
          }
        },
        grid: {
          left: "5%",
          right: "5%",
          bottom: "5%",
          top: "15%",
          containLabel: true
        },
        yAxis: {
          type: "value",
          name: '单位（座）',
          nameTextStyle: {
            color: "#ffffff"
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "rgba(133,194,255,.5)"
            }
          },
          boundaryGap: ["0", "40%"],
          splitLine: {
            show: true,
            lineStyle: {
              color: "rgba(58,112,197,.12)"
            }
          },
          splitNumber: 2,
          axisLabel: {
            color: "#ffffff"
          },
          splitArea: {
            show: false,
            areaStyle: {
              color: "rgba(58,112,197,.1)"
            }
          }
        },
        xAxis: {
          type: "category",
          data: xAxisName,
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "rgba(133,194,255,.5)"
            }
          },
          axisLabel: {
            color: "#ffffff",
            interval: 0,
            width: 80,
            overflow: "truncate",
            ellipsis: "...",
            fontSize: 12,
            rotate: 25,  //设置倾斜角度25°
          }
        },
        series: {
          type: 'bar',
          barMinWidth: 10,
          barMaxWidth: 15,
          label: {
            show: true,
            position: "top",
            borderColor: "transparent",
            borderWidth: 0,
            fontSize: 16,
            color: "#fff",
            shadowColor: "transparent",
            fontFamily: "YouSheBiaoTiHei"
          },
          itemStyle: {
            color: function (params) {
              return new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: that.policeColor[!that.isClickTwo ? params.dataIndex : 0] },
                { offset: 0.985, color: that.toRGB(that.policeColor[!that.isClickTwo ? params.dataIndex : 0], 0.1) },
                { offset: 0.985, color: that.toRGB(that.policeColor[!that.isClickTwo ? params.dataIndex : 0], 1) },
                { offset: 1, color: that.toRGB(that.policeColor[!that.isClickTwo ? params.dataIndex : 0], 1) }
              ])
            }
          },
          data: seriesData
        }
      }
      option && ChartIns1.setOption(option, true);
    },
    resetChartDataInner(obj, obj1) {
      this.outer = false;
      this.isShow = false
      this.$nextTick(() => {
        const chartDomP_Type = this.$refs.MainChartRef1;
        ChartIns1 = echarts.init(chartDomP_Type);
        ChartIns.clear();
        this.policeLevel.forEach(item => {
          item.value = obj[item.name]
        })
        this.policeType.forEach(item => {
          item.value = obj1[item.name]
        })
        const xAxisName = this.policeLevel.map(v => v.name);
        const seriesData = this.policeLevel.map(v => v.value);
        this.renderChart({
          xAxisName,
          seriesData,
          datazoom: false,
        })
        this.renderChart1({
          xAxisName: this.policeType.map(v => v.name),
          seriesData: this.policeType.map(v => v.value)
        })
      })
    },
    resetChartDataInner1() {
      this.$store.commit('SET_NAVIGATION', {
        data: this.actualData
      })
      eventBus.emit('setAnaDataOfReal', { data: this.actualData, title: '实装数字航标各局统计', index: 1 });
    },
    // 更新了接口
    resetChartDataInner2() {
      this.$store.commit('SET_NAVIGATION', {
        data: this.beRegisteredData
      })
      eventBus.emit('setAnaDataOfDesigned', { data: this.beRegisteredData, title: '航标设标数各局统计' });
    },

    backChart() {
      this.outer = true;
      this.isShow = true;
      this.isClickOne = false;
      this.isClickTwo = false;
      if (ChartIns)
        ChartIns.clear();
      if (ChartIns1)
        ChartIns1.clear();
      this.renderChart({
        xAxisName: window.SUPER_GIS_SPACE.fiaryWayAnalize.outer.name,
        seriesData: window.SUPER_GIS_SPACE.fiaryWayAnalize.outer.data,
        datazoom: !this.outer,
      })
    }
  }
};
</script>
<style lang="less" scoped>
.section-one {
  // padding-top: 40px;

  &>.title {
    background-image: url(@/components/SupermapCard/images/title-main-header-v2.png);
    background-repeat: no-repeat;
    padding: 0 10px;
    font-family: 'alimamashuheiti', Arial, Helvetica, sans-serif;
    font-size: 16px;
    color: #fff;
  }

  .divider {
    border-top: 1px dashed rgba(255, 255, 255, 0.3);
    margin: 20px 10px;
  }
}

.main-chart-ref {
  height: 200px;
}

.sub-title {
  line-height: 1.8;
  height: 27px;
  padding: 0 10px;
  display: flex;
  justify-content: space-between;

  &>.title {
    color: #fff;
    font-weight: bolder;
  }

  &>.self-icon {
    cursor: pointer;
  }
}

.title {
  color: #fff;
  font-weight: bolder;
  margin-left: 10px;
}

.echarts_Titile {
  padding: 0 10px;
}
</style>